/*
 * FreenectAdapter.cpp
 *
 */

#include "../../include/kinect/FreenectAdapter.h"
#include "../../include/kinect/FreenectAdaptee.h"
#include "../../include/Config.h"

namespace kinect {

FreenectAdapter* FreenectAdapter::_instance = 0;

FreenectAdapter::FreenectAdapter(unsigned short int id = 0) : Kinect() {
	this->_id = id;
	_freenect = new Freenect::Freenect;
	libfreenect::FreenectAdaptee& ref = _freenect->createDevice<libfreenect::FreenectAdaptee>(_id);
	_adaptee = &ref;
	_adaptee->setTiltDegrees(0);
}

FreenectAdapter::~FreenectAdapter() {
	_freenect->deleteDevice(_id);
	delete _freenect;

	// Prevenzione del dangling reference.
	_adaptee 	= NULL;
	_freenect 	= NULL;
}

FreenectAdapter* FreenectAdapter::getInstance(unsigned short int id) {
	if(_instance == 0)
		_instance = new FreenectAdapter(id);

	return _instance;
}

void FreenectAdapter::release(){
	assert(_instance != 0);

	delete _instance;
	_instance = 0;
}

unsigned short int FreenectAdapter::getId() const{
	assert(_instance != 0);

	return this->_id;
}

void FreenectAdapter::startBGRCapture() {
	assert(_instance != 0);

	_adaptee->startVideo();
	_bgr_capture = true;
}

void FreenectAdapter::stopBGRCapture() {
	assert(_instance != 0);

	_adaptee->stopVideo();
	_bgr_capture = false;
}

void FreenectAdapter::startDepthCapture() {
	assert(_instance != 0);

	_adaptee->startDepth();
	_depth_capture = true;
}

void FreenectAdapter::stopDepthCapture() {
	assert(_instance != 0);

	_adaptee->stopDepth();
	_depth_capture = false;
}

bool FreenectAdapter::isBGRStarted() const {
	assert(_instance != 0);

	return _bgr_capture;
}

bool FreenectAdapter::isDepthStarted() const {
	assert(_instance != 0);

	return _depth_capture;
}

void FreenectAdapter::getBGRFrame(cv::Mat& dest) {
	assert(_instance != 0);

	_adaptee->getVideo(dest);
}

void FreenectAdapter::getDepthFrame(cv::Mat& dest) {
	assert(_instance != 0);

	_adaptee->getDepth(dest);
}

void FreenectAdapter::alza() {
	_adaptee->setTiltDegrees(5);
}

void FreenectAdapter::abbassa() {
	_adaptee->setTiltDegrees(-5);
}

void FreenectAdapter::azzera() {
	_adaptee->setTiltDegrees(0);
}

} /* namespace kinect */
